package com.erbao.dp.visitor.asm.proxy;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static org.objectweb.asm.Opcodes.*;
/**
 * @author CaoBaoYin
 * @since 21/9/26 15:25
 */
public class ClassTransformTest {

    public static void main(String[] args) throws IOException {
        ClassReader cr = new ClassReader(ClassTransformTest.class.getClassLoader().getResourceAsStream("com/erbao/dp/visitor/asm/proxy/Tank.class"));
        ClassWriter cw = new ClassWriter(0);
        ClassVisitor cv = new ClassVisitor(ASM4, cw) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
                MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);

                if (name.contains("init")) {// 构造方法不加
                    return mv;
                }

                return new MethodVisitor(ASM4, mv) {
                    @Override
                    public void visitCode() {
                        // 静态调用
                        visitMethodInsn(INVOKESTATIC, "TimeProxy", "before", "()V", false);
                        super.visitCode();
                    }
                };
            }
        };

        //cr.accept(cw, 0);// 此时是做了一个类的拷贝
        cr.accept(cv, 0);
        byte[] bytes = cw.toByteArray();

        File file = new File("com/erbao/dp/asm/");
        file.mkdirs();

        FileOutputStream fos = new FileOutputStream(new File("com/erbao/dp/asm/tank0.class"));
        fos.write(bytes);
        fos.flush();
        fos.close();
    }

}
